<template>
  <div>
    <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品 </el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图区域 -->
      <el-card class="box-card">
        <!-- 警告提示区域 -->
        <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
        <!-- 步骤区域 -->
        <el-steps
          :space="200"
          :active="parseInt(activeIndex)"
          finish-status="success"
          align-center
        >
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <!-- tabs栏 -->
        <el-form
          :model="addGoodsForm"
          :rules="addGoodsRules"
          ref="addGoodsRef"
          label-position="top"
        >
          <el-tabs
            tab-position="left"
            v-model="activeIndex"
            :before-leave="beforeoerTabLeave"
            @tab-click="tabClicked"
          >
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addGoodsForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input
                  v-model="addGoodsForm.goods_price"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input
                  v-model="addGoodsForm.goods_weight"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input
                  v-model="addGoodsForm.goods_number"
                  type="number"
                ></el-input>
              </el-form-item>
              <!-- 级联选择器 -->
              <el-form-item label="商品分类">
                <el-cascader
                  v-model="addGoodsForm.goods_cat"
                  :options="cateList"
                  :props="{
                    expandTrigger: 'hover',
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children',
                  }"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
              <!-- 渲染表单item项 -->
              <el-form-item
                :label="item1.attr_name"
                v-for="item1 in manyTabData"
                :key="item1.attr_id"
              >
                <!-- 复选框组 -->
                <!-- <el-checkbox-group v-model="item1.attr_vals"> -->
                <el-checkbox
                  border
                  checked
                  v-for="(item2, i) in item1.attr_vals"
                  :key="i"
                  >{{ item2 }}</el-checkbox
                >
                <!-- </el-checkbox-group> -->
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <el-form-item
                v-for="item in onlyTabData"
                :key="item.attr_id"
                :label="item.attr_name"
              >
                <el-input v-model="item.attr_vals"> </el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <!-- action 图片上传的地址 -->
              <el-upload
                action="/api/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                list-type="picture"
                :headers="headerObj"
                :on-success="uploadSuccess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
              <!-- 点击 preview 预览，弹出对话框-->
              <el-dialog
                :visible.sync="previewDialogVisible"
                width="50%"
                title="图片预览"
              >
                <img :src="previewURL" alt="" class="previewImg" />
              </el-dialog>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <!-- 富文本编辑器 -->
              <quill-editor
                v-model="addGoodsForm.goods_introduce"
                ref="myQuillEditor"
              >
              </quill-editor>
              <!-- 确认添加商品按钮 -->
              <el-button
                type="primary"
                style="margin-top: 20px"
                @click="addGoods"
                >添加商品</el-button
              >
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import { reqCateList, reqCateById, reqAddGoodsList } from "../../api";
import cloneDeep from "lodash/cloneDeep";
export default {
  data() {
    return {
      // 步骤条活动的index 也是tabs v-model的值,name 的值
      activeIndex: "0",
      addGoodsForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组  级联选择器选中的数组(id值)
        goods_cat: [],
        // 上传的图片临时路径的数组
        pics: [],
        // 富文本编辑器
        goods_introduce: "",
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: [],
      },
      addGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
      },
      // 分类商品数据列表
      cateList: [],
      // 动态参数属性列表
      manyTabData: [],
      // 静态参数属性列表
      onlyTabData: [],
      // 设置上传的请求头部
      headerObj: {
        Authorization: sessionStorage.getItem("token_key"),
      },
      // 是否显示预览对话框
      previewDialogVisible: false,
      // 预览显示图片的Url地址
      previewURL: "",
    };
  },
  mounted() {
    this.getCateList();
  },
  methods: {
    // 获取分类商品数据列表
    async getCateList() {
      const result = await reqCateList();
      if (result.meta.status != 200)
        return this.$message.error(result.meta.msg);
      this.cateList = result.data;
    },
    //级联选择器选项选中了，会触发这个函数
    handleChange() {
      if (this.addGoodsForm.goods_cat.length !== 3)
        return (this.addGoodsForm.goods_cat = "");
    },
    // 切换tabs会触发这个函数
    beforeoerTabLeave(activeName, oldActiveName) {
      if (this.addGoodsForm.goods_cat.length != 3 && oldActiveName === "0") {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    // 切换tabs会触发这个函数
    async tabClicked() {
      // 访问动态属性面板
      if (this.activeIndex === "1") {
        const result = await reqCateById({ id: this.CateId, sel: "many" });
        if (result.meta.status != 200)
          return this.$message.error(result.meta.msg);
        result.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        });
        this.manyTabData = result.data;
      }
      // 访问静态属性面板
      if (this.activeIndex === "2") {
        const result = await reqCateById({ id: this.CateId, sel: "only" });
        if (result.meta.status != 200)
          return this.$message.error(result.meta.msg);

        //  result.data.forEach((item) => {
        //           item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        //         });

        this.onlyTabData = result.data;
      }
    },
    // 处理图片预览的函数
    handlePreview(file) {
      this.previewDialogVisible = true;
      this.previewURL = file.url;
      // console.log(file.response.data.url);
      // console.log(file.response.data);
      // console.log(file);
    },
    // 处理图片移除的函数
    handleRemove(file) {
      // 找到删除的这个图片的临时地址路径，  通过这个路径找到他在this.addGoodsForm.pics中对象的索引，然后根据索引删除对应的临时路径
      // console.log(file.response.data.tmp_path);
      const tmpPath = file.response.data.tmp_path;
      // 通过这个路径找到他在this.addGoodsForm.pics中对象的索引
      const tmpPathIndex = this.addGoodsForm.pics.findIndex((item) => {
        return item.pic === tmpPath;
      });
      // 然后根据索引删除对应的临时路径
      this.addGoodsForm.pics.splice(tmpPathIndex, 1);
    },
    // 文件上传成功时的钩子
    uploadSuccess(response) {
      // 获取后台返回的临时地址，并将它以对象的形式存入addGoodsForm中的pics数组中(看接口文档)
      const pic = response.data.tmp_path;
      const picinfo = { pic };
      // push到addGoodsForm中的pics数组中
      this.addGoodsForm.pics.push(picinfo);
    },
    // 确认添加商品
    addGoods() {
      // 表单预验证
      this.$refs.addGoodsRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写必要的表单项！");

        // 执行添加商品业务逻辑
        // 发请求 前要对表单数据中goods_cat做一下处理：如下
        // 对form表单进行深拷贝，以至于将goods_cat数组，转为字符串 且不妨碍级联选择器的使用
        const addForm = cloneDeep(this.addGoodsForm);
        // 直接操作addForm
        addForm.goods_cat = addForm.goods_cat.join(",");

        // 还要处理动态参数和静态属性
        // 动态参数
        this.manyTabData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          this.addGoodsForm.attrs.push(newInfo);
        });
        this.onlyTabData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addGoodsForm.attrs.push(newInfo);
        });

        addForm.attrs = this.addGoodsForm.attrs;

        // 发请求
        const result = await reqAddGoodsList(addForm);
        if (result.meta.status != 201)
          return this.$message.error(result.meta.msg);
        this.$message.success(result.meta.msg);
        this.$router.push("/goods");
        // console.log(result);
        // console.log(this.addGoodsForm);
        // console.log(addForm);
      });
    },
  },
  computed: {
    // 级联选择器中的三级分类参数的id
    CateId() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2];
      } else {
        return null;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 10px 0 !important;
}
.previewImg {
  width: 100%;
}
</style>